module MC {
    ///let url = '/api/home/call?c=' + str;
    /** 带有加载图的访问方式 */
    export function apiD(str: string, data: any = {}, fun: Function = null, Err: Function = null) {
        MC.msg.showLoad();
        api(str, data, (data: any) => {
            MC.msg.hideLoad();
            fun && fun(data);
        }, Err);
    }


    /** 带有缓存的访问方式 */
    export function apiC(str: string, data: any = {}, fun: Function = null, Err: Function = null) {
        let cache = MC.Cache.getObj('apiC' + str);
        if (cache) {
            fun(cache);
        }
        api(str, data, (data: any) => {
            fun(data);
            MC.Cache.setObj('apiC' + str, data)
        }, Err);
    }


    export function api(str: string, data: any = {}, fun: Function = null, Err: Function = null) {
        let url = '/api/app/call/' + str;
        if (str[0] == '/') {
            url = str;
        }
        if (str.indexOf('http') == 0) {
            url = str;
        }
        let head: any = {};
        /*
            if ($('#post_token').val()) {
                    head['X-CSRF-TOKEN'] = $('#post_token').val();
                }
        */
        var userInfo = JSON.parse(localStorage.getItem('userInfo'));
        if (userInfo) {
            var app_access = MC.app_access;
            /// userInfo.app_access;
            var token = userInfo.token;
            if (!data.app_access) {
                data.app_access = app_access;
                if (typeof (data.append) == 'function') {
                    data.append('app_access', app_access);
                }
            }
            if (!data.token) {
                data.token = token;
                if (typeof (data.append) == 'function') {
                    data.append('token', token);
                }
            }
        } else {
            if (!data.token) {
                data.token = '不再使用';
            }
            if (!data.app_access) {
                data.app_access = MC.app_access;
            }
        }
        let sendObj: any = {
            headers: head,
            url: url,
            type: "post",
            dataType: "json",
            data: data,
            success: function (json: any) {
                if (json.code == 0 || json.code == 200) {
                    fun && fun(json.data);
                } else {
                    MC.msg.hideLoad();
                    if (Err) {
                        Err(json.msg, json.code);
                    } else {
                        if (json.code == API.Login || json.code == -13) {
                            MC.login();
                            return;
                        }
                        MC.msg.alert(json.msg);
                    }
                }
                /*if (json.sql && json.sql.length > 0) {
                    console.log(str, json.sql);
                }*/
            },
            error: function (msg: any) {
                var json = JSON.parse(msg.responseText);
                json = json.errors;
                for (var item in json) {
                    for (var i = 0; i < json[item].length; i++) {
                        MC.msg.alert(json[item][i]);
                        MC.msg.hideLoad();
                        return; //遇到验证错误，就退出
                    }
                }
            }

        };

        if (typeof (data.append) == 'function') {
            sendObj.contentType = false;
            sendObj.processData = false;
        }

        $.ajax(sendObj);


    }

    export function gettoken() {
        var userInfo = JSON.parse(localStorage.getItem('userInfo'));
        if (userInfo) {
            return userInfo.token;
        } else {
            return false;
        }
    }

    export let HOST = 'http://www.fuzhuangchangongxiao.cn';
    export let $Pic = '/h5/images/logo-di.png';

    export let app_access = 'qSoiKwpWVge4TkaryH6MKvOdceGt7ZMaF20g8H0cnXI';

    export function pImg($src: string) {
        if (!$src) {
            return HOST + $Pic;
        }
        if ($src[0] === '/') {
            $src = HOST + $src;
        }
        return $src;
    }

    let _isclick = false;

    /***  避免多次点击的 */
    export function click(Fun: Function) {
        if (_isclick) {
            return;
        }
        _isclick = true;
        Fun();
        setTimeout(() => {
            _isclick = false;
        }, 800);
    }

    /** 移除点击状态 */
    export function reclick() {
        _isclick = false;
    }


    /** 获取get参数 */
    export function get(n: string) {
        var m = window.location.search.match(new RegExp("(\\?|&)" + n + "=([^&]*)(&|$)"));
        return !m ? "" : decodeURIComponent(m[2]);
    }


    export function cookie(name: string, value: string, options: any = null) {
        if (typeof value != 'undefined') { // name and value given, set cookie
            options = options || {};
            if (value === null) {
                value = '';
                options.expires = -1;
            }
            var expires = '';
            if (!options.expires) {
                options.expires = 70;
            }
            if (!options.path) {
                options.path = '/';
            }
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            var path = options.path ? '; path=' + options.path : '';
            var domain = options.domain ? '; domain=' + options.domain : '';
            var secure = options.secure ? '; secure' : '';
            document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
        } else { // only name given, get cookie
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    }

    export let backHref = '';

    export function back(url: string = '') {
        if (url !== '') {
            return window.open(url, '_self');
        }
        if (backHref !== '') {
            return window.open(backHref, '_self');
        }
        if (document.referrer == '') {
            return window.open('/h5', '_self');
        }
        window.history.back(-1);
        setTimeout(function () {
            window.open('/h5', '_self');
        }, 1000);
    }


    export function loadJsUrl(src: string, func: Function) {
        ///  return;
        //判断这个js文件存在直接执行回调
        var scripts = document.getElementsByTagName('script');
        /*
        for (var i in scripts)
            if (scripts[i].src == src||scripts[i].src.indexOf(src)!=-1)
                return func();*/
        for (let i = 0; i < scripts.length; i++) {
            var obj = scripts[i];
            if (obj && (obj.src.indexOf(src) != -1)) {
                return func();
            }
        }


        if (typeof func != 'function') {
            func = function () {
            };
        }
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = src;
        var head = document.getElementsByTagName('head').item(0);
        head.appendChild(script);

        script.onload = function () {
            func();
        };
    };


    export enum API {
        /** 正常 */
        ok = 0,
        /** 权限错误 */
        Permission_error = -1,
        /** 参数错误 */
        Parameter_error = -2,
        /** 没有数据 */
        nullData = -3,
        /** 需要登录 */
        Login = -1001
    }


    /**
     * 调用接口登录
     * type='pass'|'yzm'
     *
     * */
   export function loginpost(mobile: string, pwd: string, fun: Function,type='pass') {


        var regMobile = /^1[34578]\d{9}$/; //手机号码验证规则
        var regPwd = /^[0-9a-zA-Z_]{5,20}$/; //密码验证规则
        if (!regMobile.test(mobile)) {
            MC.msg.alert('手机号码未填或格式错误！');
            return;
        }
        if (!regPwd.test(pwd)) {
            MC.msg.alert('密码未填或格式错误！');
            return;
        }
        var data = {
            app_access: app_access,
            phone: mobile,
            pwd: pwd
        };
        $.ajax({
            type: 'post',
            url: "/api/member/login",
            data: data,
            success: function (res) {
                //console.log(res); return;
                if (res.code != 0) {
                    MC.msg.alert(res.msg);
                    return;
                }
                //存储用户信息
                var type = res.data.type;
                var cate = res.data.cate;
                var userInfo = {
                    token: '不再使用'
                };
                MC.Cache.setObj('user', {
                    is_company: res.data.is_company,
                    is_factory: res.data.is_factory,
                    is_yingpin: res.data.is_yingpin,
                    head: res.data.head,
                    name: res.data.name,
                    id: res.data.id
                });
                MC.msg.show('登录成功');
                fun(res.data);
                return;
            },
            error: function () {
                MC.msg.alert('操作错误！');
            }
        });

    }

    export function login() {
        //console.log("login Div");
        ///window.open('/h5/login/login.html', '_self');
        MC.msg.ShowLogin((phone: string, password: string,loginhide:Function) => {
            loginpost(phone, password, (res: any) => {
                loginhide();
            });
        });
    }


    export module API {
        /** 绑定文件上传事件并上传图片 */
        export function bindFileUp(select: any, fun: Function) {
            select.on('change', function (e: any) {
                var files = e.target.files[0] || e.dataTransfer.files[0];
                //	 console.log(files);
                var formData = new FormData();
                formData.append('img', files);
                formData.append('app_access',MC.app_access);
                MC.api(MC.HOST + '/api/member/upload/img', formData, (json: any) => {
                    fun(json.img,select);
                });
            });
        }

        /*
        String.prototype.replaceAll = function (FindText: any, RepText: any) {
            return this.replace(new RegExp(FindText, "g"), RepText);
        }*/

        export function tihuan(src: string, yuan: string, newstr: string) {
            if (!src) {
                return src;
            }
            String.prototype.replaceAll = function (FindText: any, RepText: any) {
                return this.replace(new RegExp(FindText, "g"), RepText);
            }

            return src.replaceAll(yuan, newstr);
        }


        /** 小图转换为大图 */
        export function toBigPic(src: string) {
            if (src.indexOf('small.') == -1) {
                return src;
            }
            if (src.indexOf('/uploads/') == -1) {
                return src;
            }
            src = tihuan(src, "small.", "big.");
            return src;
            ///	return src.replaceAll("small.", "big.");
        }

        /*** 极光用户id转换为系统id */
        export function jiguangIdToSytem(mc_id: string) {
            return mc_id;
            /*if (mc_id.indexOf('mc_') == 0) {
                return mc_id.substr(3);
            } else {
                return mc_id;
            }*/
        }

        /** 时间戳转为时间字符串 */
        export function timeTostr(timestamp: any, showtime = true) {
            let timestamp = parseInt(timestamp);
            if (timestamp < 9999999999) {
                timestamp *= 1000;
            }
            var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
            var Y = date.getFullYear() + '-';
            var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
            var D = date.getDate() + ' ';
            if (!showtime) {
                return Y + M + D;
            }
            var h = date.getHours() + ':';
            var m = date.getMinutes() + ':';
            var s = date.getSeconds();
            return Y + M + D + h + m + s;
        }


        let uidArray: any = [];

        let _userEvent: any = [];

        /** 获取用户信息 */
        export function getInfo(id: string = 'my', fun: Function = null) {

            if (uidArray[id]) {
                fun && fun(uidArray[id]);
                return;
            }
            window.addEventListener("getInfo" + id, (event) => {
                fun && fun(uidArray[id]);
            });
            if (_userEvent[id]) {
                return;
            }
            _userEvent[id] = true;
            MC.api('getuserinfo', {
                uid: id
            }, (json: any) => {
                uidArray[id] = json;
                var myEvent = new Event("getInfo" + id);
                if (window.dispatchEvent) {
                    window.dispatchEvent(myEvent);
                } else {
                    (<any>window).fireEvent(myEvent);
                }
                ///	fun&&fun(json);
            });
        }


        /*** 调用上传接口 */
        export function UpPic(fun: Function) {
            let input = $('<input type="file" />');
            MC.API.bindFileUp(input, (src: string) => {
                // console.log(src);
                fun(src);
            });
            input.click();
        }


        /***
         * 返回时间戳
         * 1575340549878
         */
        export function time() {
            return Date.now();
        }

        export function html2Escape(sHtml: string) {

            return sHtml.replace(/[<>&"]/g, function (c) {
                return {'<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;'}[c];
            });

        }


    }
}


$(() => {
    //	console.log('Call.getmsgUnreadCount');
    //MC.loadJsUrl('/h5/js/jiguang.js', () => {



});